package io.gps.datatransfer.codec;

import io.gps.datatransfer.command.GpsMsg;
import io.gps.datatransfer.utils.ByteUtils;
import io.gps.datatransfer.utils.SysDef;
import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;


/**
 * 设备服务器设备信息解码
 * 
 * @author bcs
 * @version 2.0, $Date: 2020-03-29  $
 */

public class GpsDecoder extends CumulativeProtocolDecoder {
	private static Logger logger = Logger.getLogger(GpsDecoder.class);
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		int len = in.remaining();
		if (len < 15){
			return false;
		}
		int pos = in.position();
		byte b = in.get();
		int msglen = 0;
		if (b == 0x7e) {
			IoBuffer msgtou = IoBuffer.allocate(12);
			byte tempcheck = in.get();
			if(tempcheck == 0x7e){
				in.position(pos+1);
				return false;
			}else{
				in.position(pos+1);
			}
			for (int i = 0; i < 12; i++) {
				byte bb = in.get();
				if (bb == 0x7d) {
					bb = in.get();
					if (bb == 0x02) {
						msgtou.put((byte) 0x7E);
					} else if (bb == 0x01) {
						msgtou.put((byte) 0x7D);
					} else {
						while (in.hasRemaining()) {
							if (in.get() == 0x7e) {
								int templostpos =in.position();
								in.position(templostpos-1);
								return false;
							}
						}
						return false;
					}
				} else {
					msgtou.put(bb);
				}
			}
			msgtou.flip();
			int msgid=msgtou.getUnsignedShort();
			int mlen = msgtou.getUnsignedShort();
			String telphone= ByteUtils.getTelphone(msgtou);
			int msgSeri= msgtou.getUnsignedShort();
			msglen = mlen & 0x3FF;
			if ((mlen & 0x2000) == 8192) {
				msglen += 15;
			}else {
				msglen += 13;
			}
			int delylen=msglen*2;
			int dellen=0;
			if (len > msglen) {
				in.position(pos + msglen);
				while (in.hasRemaining()) {
					if (in.get() == 0x7e) {
						int snflen=(in.position() - pos -dellen);
						IoBuffer iob= IoBuffer.allocate(snflen);
						iob.put(in.array(), pos , snflen );
						iob.flip();
						IoSession oldsession=SysDef.sim_session.get(telphone);
						if(oldsession!=null&&!oldsession.equals(session)){
							oldsession.closeNow();
						}
						out.write(new GpsMsg(msgid,msgSeri,telphone,iob));
						return true;
					}
				}
			} else {
				in.position(pos);
				return false;
			}
			if ((in.position() - pos) < delylen) {
				in.position(pos);
				return false;
			}
		} else {
			while (in.hasRemaining()) {
				int templostpos =in.position();
				if (in.get() == 0x7e) {
					in.position(templostpos);
					return false;
				}
			}
		}
		session.closeNow();
		return false;
	}
}
